package lb.io.utils;

import org.apache.logging.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;

public class Cmd {
    private final static Logger klog = Klog.getLogger(Cmd.class);

    private final String cmd;

    public Cmd(String cmd) {
        this.cmd = cmd;
    }

    public String execute() throws RuntimeException {
        String result = "";
        List<String> cmds = new LinkedList<>();
        cmds.add("sh");
        cmds.add("-c");
        cmds.add(this.cmd);
        ProcessBuilder pb = new ProcessBuilder(cmds);
        pb.redirectErrorStream(true);
        try {
            Process process = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
            /* 用shell返回值命令执行是否成功 */
            int exitValue = process.waitFor();
            if (exitValue == 0) {
                result = sb.toString();
            } else {
                throw new RuntimeException(String.format("%s exit %d: %s", this.cmd, exitValue, sb.toString()));
            }
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }

        return result;
    }

    public static String command(String shell) {
        klog.debug(shell);
        Cmd cmd = new Cmd(shell);
        return Strings.TrimSuffix(cmd.execute(), "\n");
    }

    public static String script(String shell) {
        Cmd cmd = new Cmd(shell);
        String result = cmd.execute().replace("\n", "");
        result = result.replace("\n", "");
        result = result.replace("\t", "");
        result = result.replace("  ", "");
        result = result.trim();
        return result;
    }

    public static String timeoutScript(final String cmd, int timeout) {
        String out = "";
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        Future<String> future = executorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return script(cmd);
            }
        });

        try {
            out = future.get(timeout, TimeUnit.SECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            future.cancel(true);
        }

        return out;
    }

    public static void main(String[] args) {
        System.out.println(System.getProperty("os.arch"));
    }
}
